/*
 * Copyright 2006 - Chris Maki
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.agoracms.model;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

@Entity
@Table(name="role")
@NamedQueries( {
	@NamedQuery(name="role.roleByName", query="select r from Role r where r.name like ?1")})
public class Role extends ModelBase {

    private static final long serialVersionUID = 3037188851343449630L;
    
    @Column(length=32)
    protected String name;
    
    @Lob
    protected String description;
 
    @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(name = "user_role", 
            joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), 
            inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
    protected Set<User> users = new HashSet<User>();
    
    public String getDescription() {
        return description;
    }
    public String getName() {
        return name;
    }
    public Set<User> getUsers() {
        return users;
    }
    
    // delegate methods for user collection
    public boolean addUser(User user) {
        user.addRole(this);
        return users.add(user);
    }
    public boolean removeUser(User user) {
        user.removeRole(this);
        return users.remove(user);
    }

    public void setDescription(String description) {
        this.description = description;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setUsers(Set<User> users) {
        this.users = users;
    }
    
    @Override
    public String toString() {
        return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)  
            .append("name", name)
            .append("description", description).toString();
    }
    
    // TODO add hashCode and equals methods
    
}
